package com.mnkjxy.beauty.net.protocal;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.mnkjxy.beauty.utils.DES;
import com.mnkjxy.beauty.values.Constant;

public class Body {

	List<BaseElement> elements = new ArrayList<>();

	/**
	 * 获取请求的集合,添加请求
	 * 
	 * @return 存放请求的集合
	 */
	public List<BaseElement> getElements() {
		return elements;
	}

	public void serializerBody(XmlSerializer serializer) {

		try {
			serializer.startTag(null, "body");
			// 序列化请求
			for (BaseElement element : elements) {
				serializer.startTag(null, "element");

				element.serializerElement(serializer);

				serializer.endTag(null, "element");
			}
			serializer.endTag(null, "body");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取完整的body,包括<body>开始结束标签
	 * 
	 * @return
	 */
	public String getWholeBody() {
		XmlSerializer serializer = Xml.newSerializer();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			serializer.setOutput(os, "utf-8");
			this.serializerBody(serializer);
			serializer.flush();
			return os.toString("utf-8");
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 截取body标签内部的,采用des加密的数据
	 * 
	 * @return
	 */
	public String getBodyInnerDESInfo() {
		String body = getWholeBody();
		System.out.println("完整的body为:" + body);
		String innerData = StringUtils.substringBetween(body, "<body>", "</body>");
		System.out.println("加密前的原始数据为:" + innerData);
		// 加密

		DES des = new DES();
		String authcode = des.authcode(innerData, "DECODE", Constant.DES_PASSWORD);

		System.out.println("body内部数据加密后为:" + authcode);
		// 解密
		System.out.println("body内部数据解密后为:" + des.authcode(authcode, "ENCODE", Constant.DES_PASSWORD));

		return authcode;
	}
}